
from flask import Blueprint, redirect,render_template, request, session, url_for
from sqlalchemy import and_
from app.models.base import db
from app.models.teacher import Teacher
from app.models.llmAnswer import LLMAnswer
from app.models.course import Course
from app.models.assignqV import AssignmentQ

teacherBP = Blueprint('teacher',__name__)

@teacherBP.route('', methods=['GET','POST'])

def get_teacher():
    t_id=session.get('id')
    t_name=session.get('name')
    if request.method == 'GET':
        return render_template('teacher.html',title='tudent',header='Sample Case',name=t_name,id=t_id)
    else :
        search_field = request.form.get('search_field', 'CName')
        search_value = request.form.get('search_value', '')

        # 添加调试信息
        print(f'Searching by {search_field} with value {search_value}')

        results = search_items(search_field, search_value)

        # 检查搜索结果
        print(f'Found {len(results)} results')

        return render_template('teacher.html', results=results, search_field=search_field, search_value=search_value,name=t_name,id=t_id)

def search_items(search_field, search_value):
    results = []

    if search_field == 'CName':
        courses = Course.query.filter(Course.CName.like(f'%{search_value}%')).all()
        for course in courses:
            for question in AssignmentQ.query.filter(AssignmentQ.CNumber==course.CNumber).all():
                for answer in LLMAnswer.query.filter(LLMAnswer.Q_id==question.Q_id).all():
                    results.append({
                        'A_id': answer.A_id,
                        'Q_id': question.Q_id,
                        'course_name': course.CName,
                        'course_number': course.CNumber,
                        'course_category': course.CCategory,
                        'Q_Text': question.Q_Text,
                        'LLM_name': answer.LLM_Name,
                        'LLM_answer': answer.LLM_Answer,
                        'score': answer.Score
                    })

    elif search_field == 'CCategory':
        courses = Course.query.filter(Course.CCategory.like(f'%{search_value}%')).all()
        for course in courses:
            for question in AssignmentQ.query.filter(AssignmentQ.CNumber==course.CNumber).all():
                for answer in LLMAnswer.query.filter(LLMAnswer.Q_id==question.Q_id).all():
                    results.append({
                        'A_id': answer.A_id,
                        'Q_id': question.Q_id,
                        'course_name': course.CName,
                        'course_number': course.CNumber,
                        'course_category': course.CCategory,
                        'Q_text': question.Q_Text,
                        'LLM_name': answer.LLM_Name,
                        'LLM_answer': answer.LLM_Answer,
                        'score': answer.Score
                    })

    elif search_field == 'CNumber':
        courses = Course.query.filter(Course.CNumber.like(f'%{search_value}%')).all()
        for course in courses:
            for question in AssignmentQ.query.filter(AssignmentQ.CNumber==course.CNumber).all():
                for answer in LLMAnswer.query.filter(LLMAnswer.Q_id==question.Q_id).all():
                    results.append({
                        'A_id': answer.A_id,
                        'Q_id': question.Q_id,
                        'course_name': course.CName,
                        'course_number': course.CNumber,
                        'course_category': course.CCategory,
                        'Q_text': question.Q_Text,
                        'LLM_name': answer.LLM_Name,
                        'LLM_answer': answer.LLM_Answer,
                        'score': answer.Score
                    })

    elif search_field == 'Score':
        try:
            score_value = float(search_value)
            tolerance = 0.01  # 调整误差范围
            llm_answers = LLMAnswer.query.filter(
                and_(
                    LLMAnswer.Score >= score_value - tolerance,
                    LLMAnswer.Score <= score_value + tolerance
                )
            ).all()
        except ValueError:
            llm_answers = []
        for answer in llm_answers:
            question = AssignmentQ.query.filter(AssignmentQ.Q_id==answer.Q_id).first()
            course = Course.query.filter(Course.CNumber==question.CNumber).first()
            results.append({
                'A_id': answer.A_id,
                'Q_id': question.Q_id,
                'course_name': course.CName,
                'course_number': course.CNumber,
                'course_category': course.CCategory,
                'Q_text': question.Q_Text,
                'LLM_name': answer.LLM_Name,
                'LLM_answer': answer.LLM_Answer,
                'score': answer.Score
            })

    return results
@teacherBP.route('/answer/<int:a_id>/<string:t_name>/<int:t_id>',methods=['GET','POST'])
def answer_detail(a_id,t_name,t_id):
    if request.method == 'GET':
        # 通过 A_id 查询对应的答案及其相关信息
        answer = LLMAnswer.query.get_or_404(a_id)
        if answer:
            # 通过 Q_id 查询相关的 AssignmentQ 对象
            question = AssignmentQ.query.get(answer.Q_id)
            if question:
                # 通过 CNumber 查询相关的 Course 对象
                course = Course.query.get(question.CNumber)

                # 确保在模板中可以使用这些信息
                return render_template('answer_detail.html', answer=answer, question=question, course=course,name=t_name,a_id=str(a_id),id=t_id)
            else:
                return "<h1>Question not found</h1>", 404
        return "<h1>Answer not found</h1>", 404
